package com.example.sports_meet.adapter;

import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.core.content.ContextCompat;

import com.example.sports_meet.MyDbHelper;
import com.example.sports_meet.R;

import java.util.ArrayList;
import java.util.List;

public class Select_Adapter extends BaseAdapter { //每一个数据行都是一个字符串数组，保存了一个数据行的所有字段
    private Context context;
    private List<String[]> itemList;
    private MyDbHelper myDbHelper;
    private String targetTable;
    private String idName;
    private String keyWord = "";
    boolean enableBtn;

    public Select_Adapter(Context context, MyDbHelper myDbHelper, String targetTable, String idName, boolean enableBtn) {
        this.context = context;
        this.myDbHelper = myDbHelper;
        this.targetTable = targetTable;
        this.idName = idName;
        itemList = new ArrayList<>();
        updateData(targetTable, keyWord);
        this.enableBtn = enableBtn;
    }

    public void updateData(String targetTable, String keyWord) {
        String selectionTemplate = ""; // 存储生成的查询条件模板
        List<String> selectionArgsList = new ArrayList<>(); // 存储查询条件中通配符的值
        SQLiteDatabase db = myDbHelper.getReadableDatabase();
        // 查询表的列信息
        Cursor cursor = db.rawQuery("PRAGMA table_info(" + targetTable + ")", null);
        if (cursor != null) {
            while (cursor.moveToNext()) {
                String columnName = cursor.getString(cursor.getColumnIndexOrThrow("name"));
                selectionTemplate += columnName + " LIKE ? OR ";
                selectionArgsList.add("%" + keyWord + "%"); // 将通配符的值添加到列表中
            }
            cursor.close();
        }
        selectionTemplate = selectionTemplate.substring(0, selectionTemplate.lastIndexOf(" OR "));
        String selection = "(" + selectionTemplate + ")";
        String[] selectionArgs = selectionArgsList.toArray(new String[0]);

        itemList.clear();
        Cursor cursor_;
        if (keyWord.length() == 0) {
            cursor_ = db.query(targetTable, null, null, null, null, null, null);
        } else {
            cursor_ = db.query(targetTable, null, selection, selectionArgs, null, null, null);
        }

        if (cursor_.getCount() == 0) {
            Toast.makeText(context, "没有数据", Toast.LENGTH_SHORT).show();
        } else {
            cursor_.moveToFirst();
            int columns = cursor_.getColumnCount();
            do {
                String[] tmp = new String[columns];
                ;
                for (int i = 0; i < columns; i++) {
                    tmp[i] = cursor_.getString(i);
                }
                itemList.add(tmp);
            }
            while (cursor_.moveToNext());
        }
        cursor_.close();
        db.close();
    }

    @Override
    public int getCount() {
        return itemList.size();
    }

    @Override
    public String[] getItem(int position) {
        return itemList.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(final int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        if (convertView == null) {
            convertView = inflater.inflate(R.layout.select_list_item, null);
        }

        LinearLayout itemLayout = convertView.findViewById(R.id.select_item_layout);
        itemLayout.removeAllViews();

        String[] itemData = getItem(position);

        for (String data : itemData) {
            TextView textView = new TextView(context);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT,
                    LinearLayout.LayoutParams.WRAP_CONTENT
            );
            params.width = 0;
            params.weight = 1;
            params.gravity = Gravity.START;
            textView.setLayoutParams(params);
            textView.setText(data);
            textView.setTextColor(ContextCompat.getColor(context, R.color.black));

            itemLayout.addView(textView);//itemLayout添加文字，有几个字段添加几个
        }
        if (enableBtn) {
            Button button = new Button(context);//itemLayout添加一个按钮
//            button.setWidth(1);
//            button.setForegroundGravity(Gravity.END);
//            button.setLayoutGravity(Gravity.END);
            button.setText("删除");
            itemLayout.addView(button);

//          Button button = convertView.findViewById(R.id.button);
            button.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    // 处理按钮单击事件
//                  Toast.makeText(context, "Button clicked for item: " + itemList.get(position), Toast.LENGTH_SHORT).show();
                    SQLiteDatabase db = myDbHelper.getWritableDatabase();
                    db.delete(targetTable, idName + "=?", new String[]{itemData[0]});
                    updateData(targetTable, keyWord);
                    notifyDataSetChanged();
                }
            });
        }
        return convertView;
    }
}
